package com.liu.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/4/29 10:08
 * @description TODO
 * 自定义基于内存的用户认证
 */
@Component
public class MemoryUserDerailsManager implements UserDetailsService {

    private  final Map<String, UserDetails> users = new HashMap();

    public MemoryUserDerailsManager() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123456");
        users.put("user",User.withUsername("user").password(encode).roles("USER").build());
        users.put("test",User.withUsername("test").password(encode).roles("TEST").build());

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("登录用户" + username);
        UserDetails user = users.get(username);

        if (user == null) {
            throw new UsernameNotFoundException(username);
        }

        return new User(
                user.getUsername(),
                user.getPassword(),
                true,           //是否启用
                true,   //用户账号是否过期
                true, //用户凭证是否过期
                true,   //用户是否未被锁定
                user.getAuthorities());//权限列表
    }


}
